package cn.com.dhcc.ddi.monitor.dao;

import java.util.Date;
import java.util.List;

import org.apache.taglibs.standard.tag.common.sql.DataSourceWrapper;
import org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader;
import org.springframework.stereotype.Repository;

import cn.com.dhcc.app.core.dao.BaseDao;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.CM;
import cn.com.dhcc.app.pub.core.util.dateformatter.DateFormatter;
import cn.com.dhcc.ddi.datasource.vo.DataSourceVo;
import cn.com.dhcc.ddi.datasource.vo.wapper.DataSourceRowWapper;
import cn.com.dhcc.ddi.monitor.vo.QuotaComputeRule;
import cn.com.dhcc.ddi.monitor.vo.QuotaValueOnTime;
import cn.com.dhcc.ddi.monitor.vo.TaskSuccessCountVo;
import cn.com.dhcc.ddi.monitor.vo.wapper.TaskSuccessCountRowWapper;
import cn.com.dhcc.ddi.task.vo.Task;
import cn.com.dhcc.ddi.task.vo.wapper.TaskRowWapper;

@Repository
public class MonitorDao extends BaseDao {

	public List<QuotaValueOnTime> getQuotaValueOnTimeByQuotaCode(String quotaCode) throws DaoException {
		WhereCondition searchParameter = new WhereCondition();
		searchParameter.where().eq("QUOTA_CODE", quotaCode)
				.orderBy(" OWNER_ID,MTIME desc");
		return getDao().listModule("根据指标编码获取指标实时值", QuotaValueOnTime.class,
				searchParameter);
	}
	
	/**
	 * 
	 * 向表中插入新收集信息
	 * @throws ServiceException
	 * @throws DaoException 
	 */
	public void insertQuotaValueOnTime(String quotaCode, String value, String OwnerId, Date mTime) throws DaoException {
		QuotaValueOnTime target = new QuotaValueOnTime();
	    target.setId(UUIDGenerator.getUUID());
		target.setQuotaCode(quotaCode);
		target.setValue(value);
		target.setOwnerId(OwnerId);
		target.setMtime(mTime);
		//target.setNeedAlert("1");
		getDao().insertModule("添加新节点状态信息", target);
	}
	
	 public QuotaComputeRule getQuotaRuleByRuleSn(Integer ruleSn) throws DaoException{
			if(ruleSn==null)return null;
			WhereCondition searchParameter = new WhereCondition();
			searchParameter.where().eq("sn", ruleSn);
			return  CM.getDao().getModule("根据指标id获取指标计算规则", QuotaComputeRule.class, searchParameter);
	}
	 
	 public void deleteHistory() throws ServiceException, DaoException {
		String sql = "truncate table " + SI_TABLE("t_ddi_monitor_history");
		getDao().delete("清空历史库", sql, new Object[] {});
	}
	 
	 /**
	 * 获取数据源实时连接状态
	 * @throws DaoException 
	 */
	public List<DataSourceVo> getDsStatus(WhereCondition searchData) throws DaoException {
		String sql = "SELECT t4.type, t4.id, t4.node_id, t3.name AS node_name, t4.CONF, t4.NAME, t4.needAlert FROM"
					 + " (SELECT t1.id, t1.node_id, t1.type, t1.NAME, t1.CONF, t2.needAlert, MAX(t2.mtime) FROM " 
					 + SI_TABLE("t_ddi_datasource") + " t1 LEFT JOIN " + SI_TABLE("t_ddi_monitor_ontime") + " t2"
					 + " ON (t2.owner_id = t1.id) WHERE t1.STATUS = 1 GROUP BY t1.NAME) AS t4"
					 + " LEFT JOIN " + SI_TABLE("t_ddi_node_info") + " t3 ON t3.id = t4.node_id ";
		
		return CM.getDao().list("获取数据源实时连接状态", sql,new DataSourceRowWapper(), searchData, new Object[]{});
	}
	
	/**
	 * 获取24小时成功次数统计
	 * @param taskId 任务id
	 * @return 
	 * @throws DaoException
	 */
	public List<TaskSuccessCountVo> getTaskMonitorCount(String taskId) throws DaoException {
		String sql = "SELECT h.hours AS hour, "
				  + " CASE "
				  + "   WHEN t4.success IS NULL AND h.hours < DATE_FORMAT(NOW(), '%H') THEN '0' "
				  + "   ELSE success "
				  + " END count FROM"
				  + " (SELECT LPAD(help_topic_id, 2, '0') hours FROM mysql.help_topic "
				  + "  WHERE help_topic_id <= 23 ORDER BY help_topic_id) h "
				  + " LEFT JOIN "
				  + " (SELECT DATE_FORMAT(t3.`LINKENDTIME`, '%H') AS duiring_time, "
				  + "  COUNT(*) AS success FROM " + SI_TABLE("t_ddi_task_log") + " t3 "
				  + "  WHERE t3.group_id IS NULL AND t3.TASK_ID=? AND t3.LINKENDTIME LIKE ?"
				  + " GROUP BY DATE_FORMAT(t3.LINKENDTIME, '%Y-%m-%d %H')) t4 "
				  + " ON t4.duiring_time=h.hours";
		
		String date = DateFormatter.getToday("yyyy-MM-dd") + "%";
				  
		return getDao().list("获取24小时成功次数统计", sql, new TaskSuccessCountRowWapper(), new Object[]{taskId, date} );
	}

}
